#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天翼云盘专用工具模块

提供天翼云盘分享数据提取、处理等专用工具函数
"""

import requests
import json
import re
import time
from typing import Dict, Any, Optional, List
from urllib.parse import urlparse, parse_qs

# 使用相对导入避免循环导入
try:
    from ..unified_logging import get_logger
    logger = get_logger(__name__)
except ImportError:
    import logging
    logger = logging.getLogger(__name__)


def get_tianyi_share_data(share_code: str, access_code: str = "", depth: int = 3) -> Dict[str, Any]:
    """
    获取天翼云盘分享数据
    
    Args:
        share_code: 分享码
        access_code: 访问码（可选）
        depth: 遍历深度
        
    Returns:
        包含分享信息和文件列表的字典
    """
    try:
        session = requests.Session()
        session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        })
        
        # 构建分享链接
        share_url = f"https://cloud.189.cn/t/{share_code}"
        
        # 获取分享页面
        response = session.get(share_url, timeout=30)
        response.raise_for_status()
        
        # 解析页面获取分享信息
        share_info = _parse_share_page(response.text, share_code)
        
        if not share_info.get('success'):
            return {
                'success': False,
                'error': share_info.get('error', '解析分享页面失败'),
                'shareInfo': {}
            }
        
        # 如果需要访问码
        if share_info.get('needAccessCode') and access_code:
            # 提交访问码
            verify_result = _verify_access_code(session, share_code, access_code)
            if not verify_result.get('success'):
                return {
                    'success': False,
                    'error': verify_result.get('error', '访问码验证失败'),
                    'shareInfo': share_info
                }
        
        # 获取文件列表
        file_list = _get_file_list(session, share_code, depth)
        
        return {
            'success': True,
            'shareInfo': share_info,
            'fileList': file_list,
            'crawlTime': time.time()
        }
        
    except requests.RequestException as e:
        logger.error(f"网络请求失败: {e}")
        return {
            'success': False,
            'error': f'网络请求失败: {str(e)}',
            'shareInfo': {}
        }
    except Exception as e:
        logger.error(f"获取天翼云盘分享数据失败: {e}")
        return {
            'success': False,
            'error': f'获取分享数据失败: {str(e)}',
            'shareInfo': {}
        }


def _parse_share_page(html_content: str, share_code: str) -> Dict[str, Any]:
    """解析分享页面"""
    try:
        # 提取分享信息
        share_info = {
            'shareCode': share_code,
            'shareName': '',
            'shareUser': '',
            'shareTime': '',
            'needAccessCode': False,
            'success': True
        }
        
        # 使用正则表达式提取分享名称
        name_match = re.search(r'<title[^>]*>([^<]+)</title>', html_content)
        if name_match:
            title = name_match.group(1).strip()
            # 移除"天翼云盘"等后缀
            share_info['shareName'] = re.sub(r'\s*-\s*天翼云盘.*$', '', title)
        
        # 检查是否需要访问码
        if '请输入访问码' in html_content or 'access_code' in html_content:
            share_info['needAccessCode'] = True
        
        # 提取分享用户信息
        user_match = re.search(r'分享者[：:]\s*([^<\n]+)', html_content)
        if user_match:
            share_info['shareUser'] = user_match.group(1).strip()
        
        return share_info
        
    except Exception as e:
        logger.error(f"解析分享页面失败: {e}")
        return {
            'success': False,
            'error': f'解析分享页面失败: {str(e)}'
        }


def _verify_access_code(session: requests.Session, share_code: str, access_code: str) -> Dict[str, Any]:
    """验证访问码"""
    try:
        # 这里应该实现具体的访问码验证逻辑
        # 由于天翼云盘的API可能会变化，这里提供一个基础框架
        
        verify_url = f"https://cloud.189.cn/api/open/share/checkAccessCode.action"
        data = {
            'shareCode': share_code,
            'accessCode': access_code
        }
        
        response = session.post(verify_url, data=data, timeout=30)
        result = response.json()
        
        if result.get('res_code') == 0:
            return {'success': True}
        else:
            return {
                'success': False,
                'error': result.get('res_message', '访问码验证失败')
            }
            
    except Exception as e:
        logger.error(f"验证访问码失败: {e}")
        return {
            'success': False,
            'error': f'验证访问码失败: {str(e)}'
        }


def _get_file_list(session: requests.Session, share_code: str, depth: int) -> List[Dict[str, Any]]:
    """获取文件列表"""
    try:
        # 这里应该实现具体的文件列表获取逻辑
        # 由于天翼云盘的API可能会变化，这里提供一个基础框架
        
        file_list = []
        
        # 模拟文件列表结构
        # 实际实现需要调用天翼云盘的API
        
        return file_list
        
    except Exception as e:
        logger.error(f"获取文件列表失败: {e}")
        return []


def extract_share_data(raw_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    提取和标准化分享数据
    
    Args:
        raw_data: 原始分享数据
        
    Returns:
        标准化后的分享数据
    """
    try:
        if not raw_data.get('success'):
            return raw_data
        
        share_info = raw_data.get('shareInfo', {})
        file_list = raw_data.get('fileList', [])
        
        # 统计信息
        total_files = len([f for f in file_list if f.get('type') == 'file'])
        total_folders = len([f for f in file_list if f.get('type') == 'folder'])
        total_size = sum(f.get('size', 0) for f in file_list if f.get('type') == 'file')
        
        extracted_data = {
            'success': True,
            'shareCode': share_info.get('shareCode', ''),
            'shareName': share_info.get('shareName', ''),
            'shareUser': share_info.get('shareUser', ''),
            'shareTime': share_info.get('shareTime', ''),
            'statistics': {
                'totalFiles': total_files,
                'totalFolders': total_folders,
                'totalSize': total_size
            },
            'fileList': file_list,
            'crawlTime': raw_data.get('crawlTime', time.time())
        }
        
        return extracted_data
        
    except Exception as e:
        logger.error(f"提取分享数据失败: {e}")
        return {
            'success': False,
            'error': f'提取分享数据失败: {str(e)}'
        }


def validate_tianyi_share_code(share_code: str) -> bool:
    """
    验证天翼云盘分享码格式
    
    Args:
        share_code: 分享码
        
    Returns:
        是否为有效的天翼云盘分享码格式
    """
    if not share_code or not isinstance(share_code, str):
        return False
    
    # 天翼云盘分享码通常是字母数字组合，长度在6-20之间
    pattern = r'^[a-zA-Z0-9]{6,20}$'
    return bool(re.match(pattern, share_code))


def parse_tianyi_share_url(url: str) -> Optional[str]:
    """
    从天翼云盘分享链接中提取分享码
    
    Args:
        url: 分享链接
        
    Returns:
        分享码，如果无法提取则返回None
    """
    if not url or not isinstance(url, str):
        return None
    
    try:
        # 匹配天翼云盘分享链接格式
        patterns = [
            r'https?://cloud\.189\.cn/t/([a-zA-Z0-9]+)',
            r'https?://cloud\.189\.cn/web/share\?code=([a-zA-Z0-9]+)',
            r'分享码[：:]?\s*([a-zA-Z0-9]+)',
        ]
        
        for pattern in patterns:
            match = re.search(pattern, url)
            if match:
                share_code = match.group(1)
                if validate_tianyi_share_code(share_code):
                    return share_code
        
        return None
        
    except Exception as e:
        logger.error(f"解析天翼云盘分享链接失败: {e}")
        return None


def build_tianyi_share_url(share_code: str) -> str:
    """
    构建天翼云盘分享链接
    
    Args:
        share_code: 分享码
        
    Returns:
        完整的分享链接
    """
    if not validate_tianyi_share_code(share_code):
        raise ValueError(f"无效的分享码: {share_code}")
    
    return f"https://cloud.189.cn/t/{share_code}"


def get_tianyi_file_download_url(file_id: str, share_code: str, session: requests.Session = None) -> Optional[str]:
    """
    获取天翼云盘文件下载链接
    
    Args:
        file_id: 文件ID
        share_code: 分享码
        session: 请求会话
        
    Returns:
        下载链接，如果获取失败则返回None
    """
    try:
        if session is None:
            session = requests.Session()
        
        # 这里应该实现具体的下载链接获取逻辑
        # 由于天翼云盘的API可能会变化，这里提供一个基础框架
        
        download_url = f"https://cloud.189.cn/api/open/file/getFileDownloadUrl.action"
        params = {
            'fileId': file_id,
            'shareCode': share_code
        }
        
        response = session.get(download_url, params=params, timeout=30)
        result = response.json()
        
        if result.get('res_code') == 0:
            return result.get('fileDownloadUrl')
        else:
            logger.error(f"获取下载链接失败: {result.get('res_message')}")
            return None
            
    except Exception as e:
        logger.error(f"获取天翼云盘文件下载链接失败: {e}")
        return None